package com.suoluo.zenadmin.service.trip;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.suoluo.zenadmin.common.CommonResp;
import com.suoluo.zenadmin.common.PageUtil;
import com.suoluo.zenadmin.common.StringUtil;
import com.suoluo.zenadmin.common.SystemType;
import com.suoluo.zenadmin.common.UBB;
import com.suoluo.zenadmin.dao.trip.TripDAO;
import com.suoluo.zenadmin.oss.OSSService;
import com.suoluo.zenadmin.oss.OSSService.OSSImageException;
import com.suoluo.zenadmin.service.ImageException;
import com.suoluo.zenadmin.service.InfoService;
import com.suoluo.zenadmin.service.ServiceException;
import com.suoluo.zenadmin.service.dest.DestFeatureCategoryService;
import com.suoluo.zenadmin.service.dest.DestService;
import com.suoluo.zenadmin.service.dest.DestTrafficService;
import com.suoluo.zenadmin.vo.PageVO;
import com.suoluo.zenadmin.vo.dest.DestFeatureCategoryVO;
import com.suoluo.zenadmin.vo.dest.DestFeatureItem2VO;
import com.suoluo.zenadmin.vo.dest.DestTraffic2VO;
import com.suoluo.zenadmin.vo.dest.DestVO;
import com.suoluo.zenadmin.vo.friend.FriendItemVO;
import com.suoluo.zenadmin.vo.trip.TripDailyFormVO;
import com.suoluo.zenadmin.vo.trip.TripDailyLocationsVO;
import com.suoluo.zenadmin.vo.trip.TripDailyVO;
import com.suoluo.zenadmin.vo.trip.TripFlightFormVO;
import com.suoluo.zenadmin.vo.trip.TripFlightVO;
import com.suoluo.zenadmin.vo.trip.TripLocationVO;
import com.suoluo.zenadmin.vo.trip.TripTripdestsVO;
import com.suoluo.zenadmin.vo.trip.TripVO;
import com.suoluo.zenadmin.vo.trip.TripdestVO;
import com.suoluo.zenadmin.vo.trip.UpdateTripDailyLocationVO;
import com.suoluo.zenadmin.vo.trip.UpdateTripTripdestVO;

public class TripServiceImpl implements TripService {

	private static final Log logger = LogFactory.getLog(TripServiceImpl.class);

	@Autowired
	private TripDAO tripDAO;

	@Resource(name = "destService")
	private DestService destService;
	@Resource(name = "ossService")
	private OSSService ossService;

	@Resource(name = "infoService")
	private InfoService infoService;

	@Resource(name = "categoryService")
	private DestFeatureCategoryService categoryService;
	@Resource(name="destTrafficService")
	private DestTrafficService destTrafficService;
	// @SuppressWarnings("rawtypes")
	// @Override
	// public List<TripDaySortVO> findListSortTripDays(int tripId,
	// boolean withContent) {
	//
	// List<TripDaySortVO> listItem = new ArrayList<TripDaySortVO>();
	//
	// // 查询行程的每日行程和行程项信息
	// List<Map> listTripItem = tripDAO.findListSortTripDay(tripId,
	// SystemType.INFO_DEST_FEATURE_ITEM);
	// Map<Integer, TripDayItemVO> destFeatureItemMap = new HashMap<Integer,
	// TripDayItemVO>();
	// Map<Integer, TripDayItemVO> hotelsMap = new HashMap<Integer,
	// TripDayItemVO>();
	// for (Map map : listTripItem) {
	// // 判断是第几天
	// Integer days = (Integer) map.get("t_trip_day");
	// int tripDayId = (Integer) map.get("t_trip_day_id");
	// TripDaySortVO curDays = null;
	// if (listItem.size() == days) {
	// curDays = listItem.get(days - 1);
	// } else {
	// curDays = new TripDaySortVO();
	// TripDaysPOJO tripDaysPOJO = new TripDaysPOJO();
	// String tripDayDesc = (String) map.get("t_trip_day_desc");
	// tripDaysPOJO.setTripDayDesc(tripDayDesc);
	// tripDaysPOJO.setTripDay(days);
	// tripDaysPOJO.setTripDayId(tripDayId);
	// curDays.setTripDay(tripDaysPOJO);
	// listItem.add(curDays);
	// }
	// TripDayItemVO tripDaysItemVO = new TripDayItemVO();
	// tripDaysItemVO.setTripItemId((Long) map.get("t_trip_item_id"));
	// tripDaysItemVO.setCategoryId((Integer) map
	// .get("t_feature_category_id"));
	// tripDaysItemVO.setCategoryImg((String) map
	// .get("t_feature_category_orig_img"));
	// tripDaysItemVO.setCategoryName((String) map
	// .get("t_feature_category_name"));
	// tripDaysItemVO.setDestId((Integer) map.get("t_dest_id"));
	// tripDaysItemVO.setDestName((String) map.get("t_dest_name"));
	// String source = (String) map.get("source");
	// String small = (String) map.get("small");
	// String normal = (String) map.get("normal");
	// tripDaysItemVO.setOrigImg(source + normal);
	// tripDaysItemVO.setMiniImg(source + small);
	// tripDaysItemVO.setPauseTime((Integer) map.get("stay_time"));
	// tripDaysItemVO.setRelId((Integer) map.get("feature_item_id"));
	// tripDaysItemVO.setSummary((String) map.get("summary"));
	//
	// tripDaysItemVO.setHotelId((Integer) map.get("rel_id"));
	// String zhname = (String) map.get("zhname");
	// String enname = (String) map.get("enname");
	// tripDaysItemVO.setTitle(StringUtil
	// .buildCompleteName(zhname, enname));
	// tripDaysItemVO.setTitleZh(zhname);
	// tripDaysItemVO.setTripItemOrder((Integer) map
	// .get("t_trip_item_order"));
	// tripDaysItemVO.setLat((BigDecimal) map.get("lat"));
	// tripDaysItemVO.setLng((BigDecimal) map.get("lng"));
	// if (withContent) {
	// if (tripDaysItemVO.getCategoryId() == SystemConfigHolder
	// .getDestFeatureHotelCategoryId()) {
	// hotelsMap.put(tripDaysItemVO.getHotelId(), tripDaysItemVO);
	//
	// } else {
	// destFeatureItemMap.put(tripDaysItemVO.getRelId(),
	// tripDaysItemVO);
	// }
	// }
	// // String itemDesc = (String) map.get("content");
	// // tripDaysItemVO.setItemDesc(UBB.decode(itemDesc));
	//
	// curDays.addTripDayItem(tripDaysItemVO);
	// }
	//
	// // 设置每个行程条目的内容
	// if (withContent) {
	// // 查询目的地特色项的文本内容
	//
	// if (!destFeatureItemMap.isEmpty()) {
	// int[] itemIds = new int[destFeatureItemMap.size()];
	// int i = 0;
	// for (Integer id : destFeatureItemMap.keySet()) {
	// itemIds[i++] = id;
	// }
	// List<BaseInfoVO> baseInfos = infoService.findDefaultBaseInfos(
	// itemIds, SystemType.INFO_DEST_FEATURE_ITEM);
	// for (BaseInfoVO baseInfo : baseInfos) {
	// TripDayItemVO item = destFeatureItemMap.get(baseInfo
	// .getDataId());
	// item.setItemDesc(UBB.decode(baseInfo.getContent()));
	// }
	// }
	//
	// // 获取酒店的内容
	// if (!hotelsMap.isEmpty()) {
	// int[] hotelIds = new int[hotelsMap.size()];
	// int i = 0;
	// for (Integer id : hotelsMap.keySet()) {
	// hotelIds[i++] = id;
	// }
	// List<BaseInfoVO> baseInfos = infoService.findDefaultBaseInfos(
	// hotelIds, SystemType.INFO_HOTEL);
	// for (BaseInfoVO baseInfo : baseInfos) {
	// TripDayItemVO item = hotelsMap.get(baseInfo.getDataId());
	// item.setItemDesc(UBB.decode(baseInfo.getContent()));
	// }
	// }
	// }
	// return listItem;
	// }

	// @Override
	// public TripViewVO findTripDetail(int tripId) {
	// TripViewVO tripViewVO = new TripViewVO();
	// // 查询行程表中行程信息
	// // 查询行程的类别统计信息
	// List<TripCategoryVO> listCategory = new ArrayList<TripCategoryVO>();
	// tripViewVO.setListCategory(listCategory);
	// // 查询行程的国家信息
	// List<CountryVO> listCountry = tripDAO.findListCountry(tripId);
	// tripViewVO.setListCountry(listCountry);
	// return tripViewVO;
	// }

	// @Override
	// public List<CountryVO> findListCountry(int tripId) {
	// return tripDAO.findListCountry(tripId);
	// }
	//
	// @Override
	// public void saveTrip(TripPOJO trip) {
	//
	// tripDAO.updateTrip(trip);
	// }

	@Override
	public void updateTripEnable(int tripId) {
		tripDAO.updateTripEnable(tripId);
	}

	/********************************************* 改版行程的Service接口的实现 ***************************************/
	@Override
	public List<TripdestVO> findListTripdest(int start, int rows,String destName) {
		if (StringUtils.hasLength(destName)) {
			destName = "%" + destName + "%";
		} else {
			destName = null;
		}
		
		return tripDAO.findListTripdest(start, rows,destName);
	}

	/**
	 * 统计行程目的地总数
	 * 
	 * @return
	 */
	@Override
	public int findTripdestCount(String destName) {
		if (StringUtils.hasLength(destName)) {
			destName = "%" + destName + "%";
		} else {
			destName = null;
		}
		return tripDAO.findTripdestCount(destName);
	}

	@Override
	public TripdestVO findTripdestById(int tripdestId) {
		TripdestVO tripdest = tripDAO.findTripdestById(tripdestId);

		return tripdest;
	}

	@Override
	public void updateTripdest(TripdestVO tripdest) {
		//修改行程目的地信息
		tripDAO.updateTripdest(tripdest);
		//同步修改行程与行程目的地关系表
		tripDAO.updateTripTripDest(tripdest);
	}

	@Override
	public List<TripLocationVO> findListTripLocation(int tripdestId, int start,
			int rows,String locationName) {
		if (StringUtils.hasLength(locationName)) {
			locationName = locationName + "%";
		} else {
			locationName = null;
		}
		
		return tripDAO.findListTripLocation(tripdestId, start, rows, locationName);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int updateSyncRemainSysDests() {
		// 1.查询已经同步过的最大目的地ID
		Integer maxDestId = tripDAO.findMaxSysDestId();
		if (maxDestId == null) {
			maxDestId = 0;
		}
		// 每次同步10条
		List<DestVO> dests = tripDAO.findRemainSysDests(maxDestId, 5);
		// List<TripdestVO> tripdests = new ArrayList<TripdestVO>(dests.size());
		for (DestVO dest : dests) {
			TripdestVO tripdest = new TripdestVO();
			tripdest.setName(dest.getZhname());
			tripdest.setDestId(dest.getDestId());
			tripdest.setImage(dest.getSource());
			// 非自定义
			tripdest.setCustom(SystemType.BIT_FALSE);
			tripdest.setLat(dest.getLat());
			tripdest.setLng(dest.getLng());
			// 系统目的地，默认审核通过
			tripdest.setStatus(SystemType.BIT_TRUE);
			tripdest.setGoogleId("");// google_id不能为空
			int tripdestId = tripDAO.addTripdests(tripdest);
			tripdest.setTripdestId(tripdestId);

			// 更新该目的地下的地点
			updateSyncTripdestLocations(tripdest);
		}
		return dests.size();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int updateSyncTripdestLocations(TripdestVO tripdest) {
		if (tripdest == null || tripdest.getTripdestId() == 0
				|| tripdest.getDestId() == 0
				|| StringUtil.isEmpty(tripdest.getName())) {
			throw new ServiceException(CommonResp.FAIL_CODE, "非法参数");
		}
		Integer maxDataId = tripDAO.findLocationMaxDataId(tripdest
				.getTripdestId());
		if (maxDataId == null) {
			maxDataId = 0;
		}
		List<DestFeatureItem2VO> items = tripDAO.findRemainFeatureItems(
				tripdest.getDestId(), maxDataId,
				SystemType.INFO_DEST_FEATURE_ITEM);
		
		//同步酒店
		Integer hotelMaxDataId = tripDAO.findHotelMaxDataId(tripdest
				.getTripdestId());
		if (hotelMaxDataId == null){
			hotelMaxDataId = 0;
		}
		List<DestFeatureItem2VO> hotels = tripDAO.findRemainHotels(tripdest.getDestId(), hotelMaxDataId, SystemType.INFO_HOTEL);
		//将酒店和地点合并保存
		items.addAll(hotels);
		// 同步目的地下的地点，除特别体验
		for (DestFeatureItem2VO item : items) {
			TripLocationVO loc = new TripLocationVO();
			loc.setCategoryId(item.getFeatureCategoryId());
			DestFeatureCategoryVO category = categoryService
					.findDestFeatureCategoryById(item.getFeatureCategoryId());
			loc.setCategoryName(category.getFeatureCategoryName());
			loc.setContent(null);
			String content = UBB.clear(item.getContent());
			loc.setSummary(StringUtil.substring(content, 128, null));
			// 非自定义地点
			loc.setCustom(SystemType.BIT_FALSE);
			loc.setDataId(item.getFeatureItemId());
			loc.setDestId(item.getDestId());
			loc.setDestName(tripdest.getName());
			loc.setImage(item.getSource());
			loc.setLat(item.getLat());
			loc.setLng(item.getLng());
			loc.setName(item.getZhname());
			loc.setRelId(item.getRelId());
			// 默认审核通过
			loc.setStatus(SystemType.BIT_TRUE);
			loc.setStayTime(item.getStayTime());
			loc.setTripdestId(tripdest.getTripdestId());
			loc.setGoogleId("");// 系统地点，google默认空串
			tripDAO.addTripLocation(loc);
		}
		// 同步交通
		int trafficSize = updateSyncTripdestTraffic(tripdest);
		return items.size() + trafficSize;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int updateSyncTripdestTraffic(TripdestVO tripdest) {
		if (tripdest == null || tripdest.getTripdestId() == 0
				|| tripdest.getDestId() == 0
				|| StringUtil.isEmpty(tripdest.getName())) {
			throw new ServiceException(CommonResp.FAIL_CODE, "非法参数");
		}
		//查询目的地下未同步过的交通信息
		List<DestTraffic2VO> list = tripDAO.findUnsyncTraffics(tripdest.getDestId());
		// 开始同步交通信息
		for (DestTraffic2VO trafficVO : list) {
				TripLocationVO loc = convertTraffic(trafficVO, tripdest);
				tripDAO.addTripLocation(loc);
		}
		return list.size();
		
	}

	private TripLocationVO convertTraffic(DestTraffic2VO trafficVO,
			TripdestVO tripdest) {
		TripLocationVO loc = new TripLocationVO();
		loc.setCategoryId(SystemType.TRIP_CATEGORY_TRAFFIC);
		loc.setCategoryName("交通");
		String content = UBB.clear(trafficVO.getContent());
		loc.setSummary(StringUtil.substring(content, 128, null));
		loc.setContent(trafficVO.getContent());
		// 非自定义地点
		loc.setCustom(SystemType.BIT_FALSE);
		loc.setDataId(trafficVO.getTrafficId());
		loc.setDestId(tripdest.getDestId());
		loc.setDestName(tripdest.getName());
		int trafficType = trafficVO.getTrafficType();
		switch (trafficType) {
		case 1:
			loc.setImage("trip_traffic/aviation.png");
			break;
		case 2:
			loc.setImage("trip_traffic/railway.png");
			break;
		case 3:
			loc.setImage("trip_traffic/highway.png");
			break;
		case 4:
			loc.setImage("trip_traffic/water_transport.png");
			break;
		default:
			loc.setImage("trip_traffic/local_transport.png");
			break;
		}
		
		 loc.setLat(trafficVO.getLat());
		 loc.setLng(trafficVO.getLng());
		loc.setName(trafficVO.getName());
		loc.setRelId(trafficType);
		// 默认审核通过
		loc.setStatus(SystemType.BIT_TRUE);
		// loc.setStayTime(item.getStayTime());
		loc.setTripdestId(tripdest.getTripdestId());
		// tripDAO.addTripLocation(loc);
		loc.setGoogleId("");// 系统地点，google默认空串
		return loc;
	}

	@Override
	public int findTripLocationCount(int tripdestId,String locationName) {
		if (StringUtils.hasLength(locationName)) {
			locationName = locationName + "%";
		} else {
			locationName = null;
		}
		return tripDAO.findTripLocationCount(tripdestId,locationName);
	}

	@Override
	public TripLocationVO findTripLocationById(int locationId) {
		return tripDAO.findTripLocationById(locationId);
	}

	@Override
	public void updateTripLocation(TripLocationVO location) {
		
		TripdestVO dest = tripDAO.findTripdestById(location.getTripdestId());
		
		location.setDestId(dest.getDestId());
		location.setDestName(dest.getName());
		//判断图片是否修改
		MultipartFile mfile = location.getMfile();
		
		String imageName = null;
		try{
			if(mfile != null && !mfile.isEmpty()){
				String img = location.getImage();
				if(img.indexOf("trip_traffic") != -1){
					img = null;
				}
				imageName = ossService.updateImage(mfile, img);
				location.setImage(imageName);
			}
			
			//更新行程地点信息
			tripDAO.updateTripLocation(location);
			//同步更新每天行程的地点信息
			tripDAO.updateTripDailyLocation(location);
		}
		catch (ImageException e) {
			throw e;
		}
		catch (Exception e) {
			ossService.deleteImage(imageName);
			throw new ServiceException(CommonResp.FAIL_CODE,"修改行程地点图片失败！",e);
		}
	}

	@Override
	public List<TripTripdestsVO> findTripTripdestsByTripId(int tripId) {
		return tripDAO.findTripTripdestsByTripId(tripId);
	}

	@Override
	public List<TripVO> findListTrip(int start, int rows) {
		return tripDAO.findListTrip(start, rows);
	}

	@Override
	public List<TripVO> findAuditedPageTrips(int page, int pageRows) {
		int start = PageUtil.calcStartRow(page, pageRows);
		return tripDAO.findAuditedPageTrips(start,pageRows);
	}

	@Override
	public int findTripCount() {
		return tripDAO.findTripCount();
	}

	@Override
	public int findAuditedTripCount() {
		return tripDAO.findAuditedTripCount();
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void updateTripStatus(int tripId, int status) {
		tripDAO.updateTripStatus(tripId, status);
	}

	@Override
	public List<TripdestVO> findAuditedTripdests() {
		return tripDAO.findAuditedTripdests();
	}

	@Override
	public TripVO findTripById(int tripId) {
		return tripDAO.findTripByTripId(tripId);
	}

	@Override
	public void updateTrip(TripVO trip) {
		String image = null;
		try {
			MultipartFile mfile = trip.getMfile();
			// 判断图片是否修改了
			if (mfile != null && !mfile.isEmpty()) {
				// 如果修改了图片，先替换图片
				image = ossService.updateImage(mfile, trip.getImage());
				trip.setImage(image);
			}

			// 更新行程信息
			tripDAO.updateTrip(trip);
		} catch (ImageException e) {
			throw e;
		} catch (Exception e) {
			ossService.deleteImage(image);
			throw new ServiceException(CommonResp.FAIL_CODE, "更新行程失败！", e);
		}
	}

	@Override
	public void updateTripTripdests(UpdateTripTripdestVO updateVO) {

		Integer tripId = updateVO.getTripId();
		// 1.验证是否需要创建一条行程
		if (tripId == null) {
			// 不存在对应的行程，需要创建一条编辑行程
			TripVO trip = new TripVO();
			trip.setStatus(SystemType.TRIP_STATUS_EIDT);
			tripId = tripDAO.addTrip(trip);
			updateVO.setTripId(tripId);
		}

		// 2.删除行程目的地
		TripTripdestsVO[] deleteTripTripdests = updateVO.getDeleteDests();
		if (deleteTripTripdests != null && deleteTripTripdests.length > 0) {
			for (TripTripdestsVO tripTripdest : deleteTripTripdests) {
				tripTripdest.setTripId(tripId);
				// 删除该行程下的目的地下的地点
				tripDAO.deleteTripdestLocations(tripTripdest);
				tripDAO.deleteTripTripdest(tripTripdest);
			}
		}

		// 3.添加关联的系统行程和用户自定义的行程目的地
		TripTripdestsVO[] addTripTripdests = updateVO.getAddDests();
		if (addTripTripdests != null && addTripTripdests.length > 0) {
			for (TripTripdestsVO dest : addTripTripdests) {
				// 3.1如果目的地没有行程目的地ID，则表示是添加的自定义目的地
				if (dest.getTripdestId() == 0) {
					if (!StringUtil.isEmpty(dest.getDestName())
							&& dest.getLat() != null && dest.getLng() != null) {
						// 验证该自定义目的地是否已经存在系统中
						TripdestVO customDest = tripDAO
								.findTripdestByGoogleId(dest.getGoogleId());
						if (customDest == null) {
							// 3.1.1 添加自定义目的地
							customDest = new TripdestVO();
							// 自定义
							customDest.setCustom(SystemType.BIT_TRUE);
							customDest.setLat(dest.getLat());
							customDest.setLng(dest.getLng());
							customDest.setName(StringUtil.substring(
									dest.getDestName(), 32, null));
							// 未审核
							customDest.setStatus(SystemType.BIT_FALSE);
							customDest.setGoogleId(dest.getGoogleId());
							customDest.setGoogleReference(dest
									.getGoogleReference());
							// 添加自定义目的地
							int tripdestId = tripDAO.addTripdests(customDest);
							customDest.setTripdestId(tripdestId);
						}

						// 添加自定义目的地和行程的关系
						TripTripdestsVO tripTripdest = new TripTripdestsVO();
						tripTripdest.setDestName(customDest.getName());
						tripTripdest.setTripdestId(customDest.getTripdestId());
						tripTripdest.setTripId(tripId);
						tripDAO.addTripTripdest(tripTripdest);
					} else {
						logger.error("custom trip dest invalid");
					}
				} else {
					// 关联系统的目的地
					TripTripdestsVO tripTripdest = new TripTripdestsVO();
					tripTripdest.setDestName(dest.getDestName());
					tripTripdest.setTripdestId(dest.getTripdestId());
					tripTripdest.setTripId(tripId);
					tripTripdest.setDestId(dest.getDestId());
					tripDAO.addTripTripdest(tripTripdest);
				}
			}
		}
	}

	@Override
	public List<TripDailyVO> findTripDailiyAndLocations(int tripId) {

		List<TripDailyVO> dailyList = tripDAO.findTripDaily(tripId);
		Map<Integer, TripDailyVO> dailyMap = new HashMap<Integer, TripDailyVO>();
		for (TripDailyVO daily : dailyList) {
			dailyMap.put(daily.getDailyId(), daily);
		}
		List<TripDailyLocationsVO> locations = tripDAO
				.findTripDailyocations(tripId);
		for (TripDailyLocationsVO loc : locations) {
			TripDailyVO daily = dailyMap.get(loc.getDailyId());
			daily.addTripLocation(loc);
		}
		return dailyList;
	}

	@Override
	public List<DestFeatureCategoryVO> findTripdestCategorys(int tripdestId) {
		List<Integer> categoryIdList = tripDAO
				.findTripdestCategoryIdList(tripdestId);
		List<DestFeatureCategoryVO> categoryList = new ArrayList<DestFeatureCategoryVO>(
				categoryIdList.size());
		DestFeatureCategoryVO traffic = null;
		for (Integer id : categoryIdList) {
			// 该类别是交通
			if (id == SystemType.TRIP_CATEGORY_TRAFFIC) {
				traffic = new DestFeatureCategoryVO();
				traffic.setFeatureCategoryId(id);
				traffic.setFeatureCategoryName("交通");
			} else {
				DestFeatureCategoryVO category = categoryService
						.findDestFeatureCategoryById(id);
				if (category != null) {
					categoryList.add(category);
				}
			}
		}
		Collections.sort(categoryList);
		if (traffic != null) {
			categoryList.add(traffic);
		}
		return categoryList;
	}

	@Override
	public List<TripLocationVO> findAuditedTripLocations(int tripdestId,
			int categoryId) {
		return tripDAO.findAuditedTripLocations(tripdestId, categoryId);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void updateTripDailyLocations(UpdateTripDailyLocationVO updateVO) {
		// 行程id
		int tripId = updateVO.getTripId();
		if (tripId == 0) {
			throw new ServiceException(CommonResp.FAIL_CODE, "trip is null");
		}
		// 1.删除单个的想去的地方
		List<TripDailyLocationsVO> deleteLocations = updateVO
				.getDeleteLocations();
		if (deleteLocations != null && !deleteLocations.isEmpty()) {
			tripDAO.deleteTripDailyLocations(deleteLocations);
		}

		// 删除行程的天数
		List<TripDailyVO> deleteDailys = updateVO.getDeleteDailys();
		if (deleteDailys != null && !deleteDailys.isEmpty()) {
			tripDAO.deleteTripDailys(deleteDailys);
		}
		//
		// // 3.更新行程的天
		List<TripDailyVO> updateDailys = updateVO.getUpdateDailys();
		List<TripDailyLocationsVO> updateDailyLocations = new ArrayList<TripDailyLocationsVO>();
		if (updateDailys != null && !updateDailys.isEmpty()) {
			int dailyNo = 0;
			for (TripDailyVO daily : updateDailys) {
				daily.setDailyNo(dailyNo++);
				daily.setTripId(tripId);
				// 该行程天已经添加了,
				if (daily.getDailyId() != 0) {
					// 添加过，则更新行程的编号
					tripDAO.updateTripDailyDailyNo(daily);
				} else {
					// 该行程天还没有添加过
					int dailyId = tripDAO.addTripDaily(daily);
					daily.setDailyId(dailyId);
				}

				int locationNo = 0;
				// 收集每天行程下的地点，更新他的locationNo,dailyId,tripId
				List<TripDailyLocationsVO> dailyLocations = daily
						.getTripDailyLocations();
				if (dailyLocations != null && !dailyLocations.isEmpty()) {
					for (TripDailyLocationsVO loc : dailyLocations) {
						locationNo++;
						loc.setLocationNo(locationNo);
						loc.setDailyId(daily.getDailyId());
						loc.setTripId(tripId);
						updateDailyLocations.add(loc);
					}
				}
			}
		}

		// 4.更新行程天下的地点数
		if (!updateDailyLocations.isEmpty()) {
			for (TripDailyLocationsVO loc : updateDailyLocations) {
				// 4.1验证是否已经添加
				if (loc.getDailyLocationId() != 0) {
					// 更新该天的的locationNo,这里不需要更新行程天的编号，因为第二步没有将一个地点移动另外一天的功能
					tripDAO.updateTripDailyLocationLocationNo(loc);
				} else {
					// 新地点的添加
					if (loc.getLocationId() == 0) {
						// 需要验证该自定义地点是否已经添加过
						TripLocationVO cloc = tripDAO
								.findTripLocationByGoogleId(loc.getGoogleId());
						if (cloc == null) {
							// 4.2添加自定义地点
							cloc = new TripLocationVO();
							cloc.setName(loc.getLocationName());
							cloc.setLat(loc.getLat());
							cloc.setLng(loc.getLng());
							cloc.setTripdestId(loc.getTripdestId());
							TripdestVO tripdest = tripDAO.findTripdestById(loc
									.getTripdestId());
							if (tripdest == null) {
								throw new ServiceException(
										CommonResp.FAIL_CODE,
										"custom location ,tripdest is null");
							}
							cloc.setDestName(tripdest.getName());// 需要验证目的地名称
							cloc.setCustom(SystemType.BIT_TRUE);// 自定义地点
							cloc.setDestId(tripdest.getDestId());
							cloc.setGoogleId(loc.getGoogleId());
							cloc.setGoogleReference(loc.getGoogleReference());
							cloc.setStatus(SystemType.BIT_FALSE);// 默认未审核
							int locationId = tripDAO.addTripLocation(cloc);
							// 绑定地点
							loc.setLocationId(locationId);
						} else {
							loc.setLocationId(cloc.getLocationId());
						}
					}
					// 4.3添加行程天下的地点
					tripDAO.addTripDailyLocation(loc);

				}
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void updateTripSort(UpdateTripDailyLocationVO updateVO) {
		int tripId = updateVO.getTripId();
		if (tripId == 0) {
			throw new ServiceException(CommonResp.FAIL_CODE, "trip is null");
		}
		TripVO trip = tripDAO.findTripByTripId(tripId);

		// 1.更新行程的的天的顺序，地点的编号
		List<TripDailyVO> dailys = updateVO.getUpdateDailys();
		if (dailys != null && !dailys.isEmpty()) {
			for (TripDailyVO daily : dailys) {
				tripDAO.updateTripDailyDailyNo(daily);
			}
		}
		// 2.更新行程地点的顺序和所属的行程的天
		List<TripDailyLocationsVO> locations = updateVO.getUpdateLocations();
		if (locations != null && !locations.isEmpty()) {
			for (TripDailyLocationsVO loc : locations) {
				tripDAO.updateLocationNoAndDailyId(loc);
			}
		}

		// 3.更新行程的总距离和行程的天数，以及名称，和图片
		if (trip == null) {
			throw new ServiceException(CommonResp.FAIL_CODE, "trip is null");
		}
		trip.setDistance(updateVO.getDistance());
		trip.setDays(updateVO.getDays());
		String tripName = trip.getName();
		if (StringUtil.isEmpty(tripName)) {
			trip.setName(updateVO.getTripName());
		}
		String image = trip.getImage();
		if (StringUtil.isEmpty(image)) {
			DestVO dest = tripDAO.findFirstTripdest(tripId,SystemType.INFO_DEST);
			if (dest != null){
				String tripdestImage = dest.getSource();
				if (!StringUtil.isEmpty(tripdestImage)) {
					String tripImage = ossService.copyImage(tripdestImage,
							trip.getName());
					trip.setImage(tripImage);
				}
				String content = UBB.clear(dest.getContent());
				trip.setSummary(StringUtil.substring(content, 128, ""));
			}
		}
		// 更新行程的基础信息
		tripDAO.updateTrip(trip);
	}

	@Override
	public List<TripDailyVO> findTripDailys(int tripId) {
		return tripDAO.findTripDaily(tripId);
	}

	@Override
	public List<TripDailyLocationsVO> findTripLocations(int tripId) {
		return tripDAO.findTripDailyocations(tripId);
	}

	@Override
	public List<TripFlightVO> findTripFights(int tripId) {
		return tripDAO.findTripFlights(tripId);
	}

	/*********************** 行程编辑接口***start **************************/
	@Override
	public List<FriendItemVO> findListAirline() {
		return tripDAO.findListAirline();
	}

	@Override
	public void updateTripContent(TripVO tripVO) {
		SimpleDateFormat sim = new SimpleDateFormat("yyyy/MM/dd HH:mm");
		try {
			tripVO.setDepartureDate(sim.parse(tripVO.getDepartureTime()));
		} catch (ParseException e) {
			throw new ServiceException(CommonResp.FAIL_CODE, "行程出发日期的转换错误！", e);
		}
		tripDAO.updateTrip(tripVO);

	}

	@Override
	public void saveFlight(TripFlightFormVO flightVO) {
		// 判断是否添加了航空信息
		if (flightVO == null) {
			return;
		}
		// 存储未添加的航班信息
		List<TripFlightVO> list = new ArrayList<TripFlightVO>();
		// 存储已添加过的航班信息
		List<TripFlightVO> oldList = new ArrayList<TripFlightVO>();
		int length = flightVO.getBack().length;
		SimpleDateFormat sim = new SimpleDateFormat("yyyy/MM/dd HH:mm");
		// 转换对象
		for (int i = 0; i < length; i++) {
			TripFlightVO tripf = new TripFlightVO();

			String departureCity = flightVO.getDepartureCity()[i];

			if (StringUtil.isEmpty(departureCity)) {
				continue;
			}

			// 航空公司Id
			tripf.setAirlineId(flightVO.getAirlineId()[i]);
			// 航空公司名称
			tripf.setAirline(flightVO.getAirline()[i]);
			// 航向
			tripf.setBack(flightVO.getBack()[i]);
			// 出发城市
			tripf.setDepartureCity(departureCity);
			// 到达城市
			tripf.setArriveCity(flightVO.getArriveCity()[i]);

			try {
				// 出发时间
				Date deparDate = sim.parse(flightVO.getDepartureTime()[i]);

				tripf.setDepartureTime(deparDate);
				// 到达时间
				tripf.setArriveTime(sim.parse(flightVO.getArriveTime()[i]));
			} catch (ParseException e) {
				throw new ServiceException(CommonResp.FAIL_CODE,
						"行程航班的出发日期或到达日期转化错误！", e);
			}
			// 出发机场
			tripf.setDepartureAirport(flightVO.getDepartureAirport()[i]);
			// 到达机场
			tripf.setArriveAirport(flightVO.getArriveAirport()[i]);
			// 航班号
			tripf.setFlightNo(flightVO.getFlightNo()[i]);
			// 舱位
			tripf.setSpace(flightVO.getSpace()[i]);
			tripf.setTripId(flightVO.getTripId());
			// 判断是否有航班Id
			if (flightVO.getFlightId() != null ) {
				Integer flightId = flightVO.getFlightId()[i];
				// 根据是否有无航班Id存放到添加或修改的容器
				if (flightId != null) {
					tripf.setFlightId(flightId);
					oldList.add(tripf);
				}
				else {
					list.add(tripf);
				}
			} 

		}
		// 保存未添加过的航班信息信息
		if (!list.isEmpty()) {
			tripDAO.saveFlight(list);
		}

		// 修改已添加的过的航班信息
		if (!oldList.isEmpty()) {
			tripDAO.updateFlight(oldList);
		}

	}

	@Override
	public void saveDaily(TripDailyFormVO dailyFormVO) {
		// 保存每天行程信息
		// 保存每天行程地点信息
		// tripDAO.saveDaily(dailyVO);
	}

	// private String getAirline(int airlineId) {
	//
	// Map<Integer, String> map = new HashMap<Integer, String>();
	//
	// List<FriendItemVO> airline = tripDAO.findListAirline();
	//
	// for (FriendItemVO friendItemVO : airline) {
	// map.put(friendItemVO.getFriendItemId(),
	// friendItemVO.getFriendItemName());
	// }
	//
	// return map.get(airlineId);
	// }
	@Override
	public void updateTripImage(TripVO trip, MultipartFile file) {
		String source = null;
		try {

			// 记录老的图片
			String oldSource = trip.getImage();
			if(oldSource != null){
				source = ossService.updateImage(file, oldSource);
			}
			else
			{
				source = ossService.putImage(file);
			}
			trip.setImage(source);

			// 更新数据
			tripDAO.updatetTripImage(trip);

		} catch (OSSImageException e) {
			throw new ServiceException(CommonResp.FAIL_CODE, "行程图片替换失败", e);
		} catch (Exception e) {
			ossService.deleteImage(source);
			throw new ServiceException(CommonResp.FAIL_CODE, "服务器异常", e);
		}

	}

	@Override
	public void deleteFlight(int flightId) {
		tripDAO.deleteFlight(flightId);
	}

	/*********************** 行程编辑接口***end **************************/

	@Override
	public TripDailyVO findTripDailyById(int dailyId) {

		return tripDAO.findTripDailyById(dailyId);
	}

	@Override
	public List<TripDailyLocationsVO> findDailyLocations(int dailyId) {
		return tripDAO.findDailyLocations(dailyId);
	}

	@Override
	public void updateTripDaily(TripDailyFormVO dailyVO) {
		// 更新每天行程信息
		tripDAO.updateTripDaily(dailyVO);
		// 封装每天行程下的自定义地点信息
		List<TripDailyLocationsVO> list = new ArrayList<TripDailyLocationsVO>();
		if (dailyVO.getLocationName() != null
				&& dailyVO.getLocationName().length > 0) {

			int len = dailyVO.getLocationName().length;
			for (int i = 0; i < len; i++) {
				TripDailyLocationsVO locat = new TripDailyLocationsVO();
				int categoryId = dailyVO.getCategoryIds()[i];
				locat.setCategoryId(categoryId);
				locat.setCategoryName(categoryService
						.findDestFeatureCategoryById(categoryId)
						.getFeatureCategoryName());
				locat.setContent(dailyVO.getContents()[i]);
				locat.setDailyLocationId(dailyVO.getDailyLocationIds()[i]);
				locat.setLocationId(dailyVO.getLocationIds()[i]);
				locat.setStayTime(dailyVO.getStayTimes()[i]);
				locat.setContent(dailyVO.getContents()[i]);
				locat.setSummary(dailyVO.getSummarys()[i]);
				locat.setLocationName(dailyVO.getLocationName()[i]);
				list.add(locat);
			}
			// 更新每天行程下自定义地点信息
			tripDAO.updateTripLocation(list);
			// 更新自定义地点对应每天行程
			tripDAO.updateDailyLocation(list);
		}

	}

	@Override
	public void updateLocationImage(int locationId, MultipartFile file) {

		String imgName = null;
		try {

			// 查询自定义地点信息
			TripLocationVO location = tripDAO.findTripLocationById(locationId);

			String imgUrl = location.getImage();
			// 如果没有图片，则直接上传图片
			if (StringUtil.isEmpty(imgUrl)) {
				imgName = ossService.putImage(file);
			} else {
				// 如果已经有图片了，则替换图片
				imgName = ossService.updateImage(file, imgUrl);
			}
			// location.setImage(imgName);
			// 然后更新到数据库
			tripDAO.updateTripLocationImage(locationId, imgName);

		} catch (ImageException e) {
			throw e;
		} catch (Exception e) {
			throw new ServiceException(CommonResp.FAIL_CODE, "更新每日行程图片失败！", e);
		}
	}

	@Override
	public void updateTripStatus(int tripId) {

		tripDAO.updateTripStatus(tripId, SystemType.TRIP_STATUS_AUDITED);
	}

	@Override
	public List<TripVO> findListExpireTrip(PageVO page) {
		int rows = page.getRows();
		int currpage = page.getPage();
		int start = PageUtil.calcStartRow(currpage, rows);
		Date date = new Date();
		return tripDAO.findListExpireTrip(date,start,rows);
	}

	@Override
	public int findExpireTripCount() {
		Date date = new Date();
		return tripDAO.findExpireTripCount(date);
	}

	@Override
	public List<TripdestVO> findListTripDests() {
		 
		return tripDAO.findListTripDests();
	}

}
